package model

import (
	"fmt"
	"gowork/dynamicCheckSheet/utils"
	"strconv"
	"strings"
	"sync"
	"time"
)

type Order struct {
	OrderId int64 `xorm:"pk autoincr"`
	OrderState int
	NextSinglePersonId int64
	NextSinglePersonName string
	Commodity string
	CommodityList []*Commodity `xorm:"-"`
	TotalPrice float64
	ProvinceId int64
	RegionId int64
	CreatedAt time.Time
  	UpdatedAt time.Time
}

func (o *Order)InsertOrder(ov *Order){
	x.Insert(ov)
}

var lock sync.Mutex

func (o *Order)InsertOrderAsync(ov *Order) (map[string]interface{}, error){

	lock.Lock()

	ok := false
	var stockList [][]interface{}
	goodList := strings.Split(ov.Commodity, ",")
	for _, good := range goodList {
		goodInfo := strings.Split(good, "*")

		var c Commodity
		x.Where("commodity_id = ?", goodInfo[1]).Get(&c)

		total, err := strconv.Atoi(goodInfo[3])
		if err != nil{

			lock.Unlock()

			return nil, err
		}

		if c.Stock < total{

			ok = true

			lock.Unlock()

			return map[string]interface{}{"message":goodInfo[0] + "库存不足", "code":400}, nil
		}

		stockInfo := []interface{}{c, total}
		stockList = append(stockList, stockInfo)
	}

	fmt.Println("ok：", ok)
	if !ok {
		for _, s := range stockList {
			c := s[0].(Commodity)
			t := s[1].(int)
			c.Stock -= t
			x.Where("commodity_id = ?", c.CommodityId).Update(&c)
		}
	}

	ov.CreatedAt = time.Now()
	ov.UpdatedAt = time.Now()
	x.Insert(ov)

	lock.Unlock()

	return map[string]interface{}{"message":"下单成功", "code":200}, nil
}

func (o *Order) Confirmation(oId int64) (map[string]interface{}, error){

	w := new(utils.Worker)

	var ov Order
	x.Id(oId).Get(&ov)

	var pe Province
	x.Id(ov.ProvinceId).Get(&pe)

	if pe.RegionId != 1 {

		ov.RegionId = pe.RegionId
		fmt.Println("ov.RegionId：", ov.RegionId)

		var cnv *CheckNode
		cn := cnv.QueryFirstNode(ov.RegionId)

		var p = Paper{
			PaperId:     w.GetId(),
			PaperState:  1,
			OrderId:     ov.OrderId,
			TotalPrice:  ov.TotalPrice,
			CheckNodeId: cn.CheckNodeId,
			RegionId:    ov.RegionId,
			RoleId:      cn.RoleId,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		}
		x.Insert(&p)

		ov.OrderState = 2
		x.Id(oId).Update(ov)
	}else {
		ov.OrderState = 3
		x.Id(ov.OrderId).Update(ov)
	}

	return map[string]interface{}{"message": "成功","code":"200"}, nil
}


